package com.shj.config.security;

import com.alibaba.fastjson.JSONObject;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description 自定义失败处理器
 * @Author songhuajian
 * @Date 2020/1/11 22:02
 **/
@Component
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {


    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        Map<String, String> map = new HashMap<>();
        map.put("code", "500");
        map.put("msg", exception.getMessage());

        String json = JSONObject.toJSONString(map);

        // 失败返回json
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().append(json);

//        response.setContentType("application/json;charset=utf-8");
//        response.setStatus(500);
//        PrintWriter out = response.getWriter();
//        RespBean respBean = RespBean.error("访问失败!");
//        if (authException instanceof InsufficientAuthenticationException) {
//            respBean.setMsg("请求失败，请联系管理员!");
//        }
//        out.write(new ObjectMapper().writeValueAsString(respBean));
//        out.flush();
//        out.close();
    }
}
